<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>页面切换</title>
</head>
<button onclick="stay()">停留时间</button>

<body>
    <script>
        var pageOpen = new Date();

        var hiddenProperty = 'hidden' in document ? 'hidden' :
            'webkitHidden' in document ? 'webkitHidden' :
                'mozHidden' in document ? 'mozHidden' :
                    null;
        var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
        var onVisibilityChange = function () {
            // 切换页面
            if (!document[hiddenProperty]) {
                pageOpen = new Date();
            } else {
                console.log('继续');
                console.log(stay());
            }
        }
        document.addEventListener(visibilityChangeEvent, onVisibilityChange);

        function stay() {

            let pageClose = new Date();

            let minutes = (pageClose.getMinutes() - pageOpen.getMinutes());

            let seconds = (pageClose.getSeconds() - pageOpen.getSeconds());

            let time = (seconds + (minutes * 60));

            return time
        }
    </script>
</body>

</html>